#!/usr/bin/env python
# -*- coding: utf-8 -*-


from module_interfaces import CLI
from utils.log import logger
from utils.tests import init_test_info
from subcommandflow import SubcommandFlow
name = 'fetch'


class Subcommand(CLI):
    def configure(self, parser):
        lparser = parser.add_parser(name, help='fetch tests codes to cache')
        lparser.set_defaults(subcommand=name.lower())
        lparser = parser.add_parser('install', help='install tests')
        lparser.add_argument(
            '--keep', action="store_true",
            help='Keep the build path after installation')
        lparser.set_defaults(subcommand='install')
        lparser = parser.add_parser('uninstall', help='uninstall tests')
        lparser.set_defaults(subcommand='uninstall')
        lparser = parser.add_parser('archive', help='archive test results')
        lparser.set_defaults(subcommand='archive')
        group = lparser.add_mutually_exclusive_group()
        group.add_argument(
            '--tools', action='store_true', default=False,
            help='Archive run tools includes tools, tests, results')
        group.add_argument(
            '--results', action='store_true', default=True,
            help='Archive results includes cache build run and result')
        lparser.add_argument(
            '--name', type=str, default=None, help="Name of Job and tar file"
        )
        lparser.add_argument(
            '--tar', action='store_true', default=False,
            help="Archive with tar"
        )
        lparser.add_argument(
            '--suite', type=str, action="append", default=[],
            help="Specify testsuites for Archive"
        )

        logger.debug("Subcommand: CLI configure")

    def run(self, appconf):
        logger.debug("Subcommand: CLI run")
        if appconf.subcommand == 'archive':
            with SubcommandFlow(appconf) as subcomand:
                subcomand.run()
        else:
            for suite in appconf.refine_test_list():
                logger.debug("Subcommand on {}".format(suite))
                testconf = init_test_info(suite, appconf)
                # config['testinfo'] = testinfo
                with SubcommandFlow(testconf) as subcommand:
                    subcommand.run()
